package com.wx.registerclient.proxy;

import com.wx.registerclient.annotation.PathMapping;
import com.wx.registerclient.config.HttpClientConfig;
import com.wx.registerclient.config.RemoteTransfer;
import com.wx.registerclient.configuration.NBServerConfigProperties;
import com.wx.registerclient.entity.ServerInfomation;
import org.nd4j.shade.jackson.databind.ObjectMapper;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

/**
 * 动态代理接口的
 * 具体逻辑实现类
 */
@Component
public class RemoteInvokeHandler implements InvocationHandler{

    @Autowired
    private NBServerConfigProperties nbServerConfigProperties;

    private static  HttpClientConfig httpClientConfig=new HttpClientConfig();

    private static  RemoteTransfer remoteTransfer=new RemoteTransfer();

    private Class<?> interfaceType;

    public RemoteInvokeHandler() {
    }

    public RemoteInvokeHandler(Class<?> interfaceType) {
        this.interfaceType=interfaceType;
    }


    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

        // 获得注册中心的地址与端口号
        String  registerPort = nbServerConfigProperties.getRegisterPort();
        String registerHost = nbServerConfigProperties.getRegisterHost();

        // 获得具体路径
        PathMapping pathMapping = method.getAnnotation(PathMapping.class);
        String path = pathMapping.path();
        // 获得服务的名字
        String serverName = pathMapping.serverName();
        // 获得请求的接口的服务名
        ServerInfomation infomation = httpClientConfig.getObject(serverName, registerHost,registerPort );
        System.out.println(infomation);
        //获得目标ip地址与端口号
        int port = infomation.getPort();
        String ip = infomation.getIp();

        // 发送http请求,所有参数以json字符串传递过去
        ObjectMapper mapper = new ObjectMapper();

        String json="";
        if(args!=null){
            for (Object arg : args) {
                json+=mapper.writeValueAsString(arg);
            }
        }

        // 获得返回值类型
        Class<?> returnType = method.getReturnType();

        // 请求的url
        String url="http://"+ip+":"+port+path;
        Object result = remoteTransfer.getResult(returnType, url, args);
        // 返回结果
        return result;
    }




}
